import pymysql
import json
import os
import socket
from redis import Redis
from flask import Flask, redirect, url_for, request, render_template
import datetime

app = Flask(__name__)
redis = Redis(host=os.environ.get('REDIS_HOST', 'redis'), port=6379)



def favorite_colors():
    config = {
        'user': 'root',
        'password': 'root',
        'host': 'mysql',
        'port': 3306,
        'database': 'knights'
    }
    connection = pymysql.connect(**config)
    cursor = connection.cursor()
    cursor.execute('SELECT * FROM favorite_colors')
    results = [{name: color} for (name, color) in cursor]
    cursor.close()
    connection.close()

    return results


@app.route('/')
def index() -> str:
    return json.dumps({'favorite_colors': favorite_colors()})


@app.route('/redis')
def hello():
    redis.incr('hits')
    return 'Hello Container World! I have been seen %s times and my hostname is %s.\n' % (
    redis.get('hits'), socket.gethostname())


